import path from 'path';
import multer from 'multer';
const initUpload = function (size = 5 * 1024 * 1024, typeReg = /jpeg|jpg|png|gif/, filePath = 'public/upload/') {
    const storage = multer.diskStorage({
        destination: function (req, file, next) {
            next(null, filePath);
        },

        filename: function (req, file, next) {
            let filename = (new Date().getTime()) + Math.ceil(Math.random() * 10000);
            let ext = path.extname(file.originalname);
            filename = filename + ext;
            next(null, filename);
        },
    });

    const upload = multer({
        storage: storage,
        limits: {
            fileSize: size,
        },
        fileFilter: function (req, file, next) {
            const filetypes = typeReg;
            const mimetype = filetypes.test(file.mimetype);
            const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
            if (mimetype && extname) {
                next(null, true);
            } else {
                next("只允许上传jpeg、jpg、png、gif文件!")
            }
        },
    });
    return upload;
};

export default initUpload;
